﻿"""
差旅费报销单，计算出差时间
"""
import clr
from System import *


def AfterBindData(e):
	if str(this.Model.GetValue("FDocumentStatus")) == "Z":
		this.Model.SetValue("FDays", 0)
		this.Model.SetValue("FTravelDays", 0)

def AfterCreateNewEntryRow(e):
	key = str(e.Entity.Key)
	if key == "FEntity":
		this.Model.SetValue("FDays", 0, e.Row)
	elif key == "FScheduleEntity":
		this.Model.SetValue("FTravelDays", 0, e.Row)

def DataChanged(e):
	key = str(e.Field.Key)
	if key in ("FTravelStartDate", "FTravelEndDate"):
		# 明细表体
		entity = this.Model.DataObject["ER_ExpenseReimbEntry"]
		for i, row in enumerate(entity):
			st = "" if row["TravelStartDate"] is None else str(row["TravelStartDate"])
			et = "" if row["TravelEndDate"] is None else str(row["TravelEndDate"])
			if st == "" or et == "":
				this.Model.SetValue("FDays", 0, i)
				continue
			day = CalculateDay(st, et)
			this.Model.SetValue("FDays", day, i)
	elif key in ("FStartDate", "FFinishDate"):
		# 行程信息表体
		entity = this.Model.DataObject["FScheduleEntity"]
		for i, row in enumerate(entity):
			st = "" if row["FStartDate"] is None else str(row["FStartDate"])
			et = "" if row["FFinishDate"] is None else str(row["FFinishDate"])
			if st == "" or et == "":
				this.Model.SetValue("FTravelDays", 0, i)
				continue
			day = CalculateDay(st, et)
			this.Model.SetValue("FTravelDays", day, i)


def CalculateDay(st_str, et_str):
	"""计算出差时间
	"""
	st = DateTime.Parse(st_str)
	et = DateTime.Parse(et_str)
	# 开始时间大于等于结束时间
	if st.CompareTo(et) >= 0:
		return 0
	# 同一天
	if et.Day == st.Day:
		return 1 if st.Hour < 12 and et.Hour > 12 else 0.5
	# 非同一天
	first = 0.5 if st.Hour >= 12 else 1
	end = 0.5 if et.Hour <= 12 else 1
	met = DateTime.Parse(et_str.split(" ")[0]).ToUniversalTime().Ticks
	mst = DateTime.Parse(st_str.split(" ")[0]).AddDays(1).ToUniversalTime().Ticks
	middle = (met - mst) / 10000000 / 3600 / 24
	return first + middle + end
